<template>
  <div class="topic-list-container">
    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="left-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加专题</el-button>
        <el-button type="info" icon="el-icon-refresh" @click="getTopicsList">刷新</el-button>
      </div>
      <div class="right-actions">
        <el-input v-model="searchTitle" placeholder="搜索专题名称" prefix-icon="el-icon-search" clearable
          class="search-input" @clear="handleSearch" @keyup.enter.native="handleSearch">
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>
    
    <!-- 专题列表表格 -->
    <el-card shadow="hover" class="table-card">
      <div class="topics-list" v-loading="loading" element-loading-text="加载中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.7)">
        <el-table
          :data="topicsList"
          style="width: 100%"
          border
          stripe
          :header-cell-style="{backgroundColor: '#f5f7fa', color: '#606266'}"
          v-if="topicsList.length > 0"
        >
          <el-table-column prop="topicId" label="专题ID" width="200" align="center"></el-table-column>
          <el-table-column prop="topicName" label="专题名称" min-width="150"></el-table-column>
          <el-table-column prop="description" label="专题描述" min-width="250">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.description" placement="top" :disabled="scope.row.description.length < 30">
                <span>{{ scope.row.description.length > 30 ? scope.row.description.substring(0, 30) + '...' : scope.row.description }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="createUser" label="创建人" width="120" align="center"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="170" align="center">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button-group class="operation-btns">
                <el-tooltip content="编辑" placement="top">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty v-if="topicsList.length === 0" description="暂无专题数据"></el-empty>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑专题对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增专题' : '编辑专题'"
      :visible.sync="dialogVisible"
      width="700px"
      @close="resetForm"
      center
    >
      <el-form :model="topicForm" :rules="formRules" ref="topicForm" label-width="80px" status-icon>
        <el-form-item label="名称" prop="topicName">
          <el-input v-model="topicForm.topicName" placeholder="请输入专题名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            :rows="8"
            placeholder="请输入专题描述"
            v-model="topicForm.description"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'TopicsManagement',
  data() {
    return {
      // 列表数据
      topicsList: [],
      // 分页相关
      pageNum: 1,
      pageSize: 10,
      total: 0,
      // 筛选条件
      searchTitle: '',
      statusFilter: '',
      // 加载状态
      loading: false,
      submitting: false,
      // 对话框控制
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      // 表单数据
      topicForm: {
        topicId: '',
        topicName: '',
        description: '',
        createTime: '',
        createUser: '',
        token: localStorage.getItem('token')
      },
      // 表单验证规则
      formRules: {
        topicName: [
          { required: true, message: '请输入专题名称', trigger: 'blur' },
          { min: 2, max: 50, message: '专题名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入专题描述', trigger: 'blur' },
          { min: 10, max: 255, message: '描述长度在 10 到 255 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getTopicsList();
  },
  methods: {
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 获取话题列表
    getTopicsList() {
      this.loading = true;
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        topicName: this.searchTitle,
        token:''
      };
      
      // 判断当前用户角色是否为戏曲家(roleid为3)
      const roleId = localStorage.getItem('roletype');
      if (roleId === '3') {
        // 如果是戏曲家，则只查询该用户创建的话题
        const token = localStorage.getItem('token');
        params.token = token;
      }
      
      service.get('/api/forum/topic/getTopicList', {params})
        .then(res => {
          if (res.code === 200) {
            this.topicsList = res.data.list || [];
            this.total = res.data.total || 0;
          } else {
            this.$message.error(res.msg || '获取话题列表失败');
          }
        })
        .catch(error => {
          console.error('获取话题列表出错:', error);
          this.$message.error('网络错误，请稍后重试');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 搜索处理
    handleSearch() {
      this.pageNum = 1;
      this.getTopicsList();
    },
    
    // 分页大小变化
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.getTopicsList();
    },
    
    // 当前页变化
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.getTopicsList();
    },
    
    // 添加话题
    handleAdd() {
      this.dialogType = 'add';
      this.dialogVisible = true;
      this.resetForm();
    },
    
    // 编辑话题
    handleEdit(row) {
      this.dialogType = 'edit';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.topicForm = {
          topicId: row.topicId,
          topicName: row.topicName,
          description: row.description,
          createTime: row.createTime,
          createUser: row.createUser,
          token: localStorage.getItem('token')
        };
      });
    },
    
    
    // 删除话题
    handleDelete(row) {
      this.$confirm('此操作将永久删除该话题, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.delete(`/api/forum/topic/deleteTopic/${row.topicId}`, {
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getTopicsList();
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        }).catch(error => {
          console.error('删除话题出错:', error);
          this.$message.error('网络错误，请稍后重试');
        });
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 提交表单
    submitForm() {
      this.$refs.topicForm.validate(valid => {
        if (valid) {
          this.submitting = true;
          
          // API路径根据操作类型确定
          const api = this.dialogType === 'add' 
            ? service.post('/api/forum/topic/addTopic', this.topicForm)
            : service.put('/api/forum/topic/updateTopic', this.topicForm);

           api
            .then(res => {
              if (res.code === 200) {
                this.$message.success(this.dialogType === 'add' ? '新增话题成功' : '更新话题成功');
                this.dialogVisible = false;
                this.getTopicsList();
              } else {
                this.$message.error(res.msg || (this.dialogType === 'add' ? '新增话题失败' : '更新话题失败'));
              }
            })
            .catch(error => {
              console.error(this.dialogType === 'add' ? '新增话题出错:' : '更新话题出错:', error);
              this.$message.error('网络错误，请稍后重试');
            })
            .finally(() => {
              this.submitting = false;
            });
        } else {
          return false;
        }
      });
    },
    
    // 重置表单
    resetForm() {
      if (this.$refs.topicForm) {
        this.$refs.topicForm.resetFields();
      }
      this.topicForm = {
        topicId: '',
        topicName: '',
        description: '',
        createTime: '',
        createUser: '',
        token: localStorage.getItem('token')
      };
    }
  }
}
</script>

<style scoped>
.topic-list-container {
  padding: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.left-actions {
  display: flex;
  align-items: center;
}

.right-actions {
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
}

.topics-list {
  min-height: 300px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.operation-btns .el-button {
  padding: 7px 12px;
}
</style> 